#include "qlife.h"
#include "dna.h"

QLife::QLife ( QGame *parent, Dna* dna, long n, int width, int height ) : QThread ( ( QObject* ) parent )
{
	alive = true;
	pregnant = false;

	id = n;

	this -> width = width;
	this -> height = height;

	age = 0;
	energy = 100;
	pregnanceDuration = 0;

	this -> dna = dna;
}

bool QLife::isAlive()
{
	return alive;
}

bool QLife::isPregnant()
{
	return pregnant;
}

long QLife::getId()
{
	return id;
}

int QLife::getWidth()
{
	return width;
}

int QLife::getHeight()
{
	return height;
}

Dna* QLife::getDna()
{
	return dna;
}

float QLife::getAge()
{
	return age;
}

float QLife::getX()
{
	return x;
}

float QLife::getY()
{
	return y;
}

void QLife::setX ( float x )
{
	this -> x = x;
}

void QLife::setY ( float y )
{
	this -> y = y;
}

float QLife::getEnergy()
{
	return energy;
}

void QLife::setSelected ( bool select )
{
	if ( select ) collectData();
}

float QLife::eat()
{
	if ( energy <= 0 )
	{
		return 0;
	}
	else
	{
		energy--;
		return 1;
	}
}

void QLife::update()
{
	age = age + 0.05;

	// die because of age
	if ( ( age > dna -> getMaxAge() ) && isAlive() )
	{
		alive = false;
		initDecay();
	}

	// die because of too less energy
	if ( energy <= 0 )
	{
		if ( alive )
		{
			alive = false;
			initDecay();
		}
		else
		{
			quit();
		}
	}

	// get pregnant if everything is fine
	if ( energy >= 150 && !pregnant )
	{
		pregnant = true;
		pregnanceDuration = dna -> getPregnanceDuration();
	}

	// emit birth if pregnance is over
	if ( ( pregnanceDuration <= 0 ) && pregnant )
	{
		pregnant = false;
		energy = energy - 50;
		emit ( birth ( new Dna ( dna ) ) );
	}
	// beeing pregnant
	else if ( pregnant )
	{
		pregnanceDuration--;
	}

	think();
}


int QLife::getPregnanceDuration()
{
	return pregnanceDuration;
}
